"""
models.py

App Engine datastore models

"""

import aetycoon as dbExt
from google.appengine.ext import db

class ExceptionNotFound(Exception):
	pass

class Alliance(db.Model):
	name = db.StringProperty(required=True)
	searchableName = dbExt.LowerCaseProperty(name)
	ticker = db.StringProperty(required=True)
	searchableTicker = dbExt.LowerCaseProperty(ticker)
	updated = db.DateTimeProperty(required=True, auto_now=True)
	created = db.DateTimeProperty(required=True, auto_now_add=True)
	
	@classmethod
	def getByEveId(cls, eveId):
		return Alliance.get_by_key_name(str(eveId))

	@classmethod		
	def updateOrAddFromApi(cls, record):
		eveId = str(record.allianceID)
		name = str(record.name)
		ticker = str(record.shortName)
		
		changed = False

		alliance = Alliance.get_or_insert(eveId,
						name=name,
						ticker=ticker)
		if name != alliance.name:
			alliance.name = name
			changed = True
		if ticker != alliance.ticker:
			alliance.ticker = ticker
			changed = True
		return (alliance, changed)

class Corporation(db.Model):
	name = db.StringProperty(required=True)
	searchableName = dbExt.LowerCaseProperty(name)
	ticker = db.StringProperty(required=True)
	searchableTicker = dbExt.LowerCaseProperty(ticker)
	updated = db.DateTimeProperty(required=True, auto_now=True)
	created = db.DateTimeProperty(required=True, auto_now_add=True)

	@classmethod
	def getByEveId(cls, eveId):
		return Corporation.get_by_key_name(str(eveId))
	
class Character(db.Model):
	userId = db.StringProperty(required=True)
	apiKey = db.StringProperty(required=True)
	characterId = db.StringProperty(required=True)
	name = db.StringProperty()
	searchableName = dbExt.LowerCaseProperty(name)
	user = db.UserProperty()
	
	@classmethod
	def getUsersCharacters(cls, user):
		query = db.Query(Character)
		query.filter('user = ', user)
		query.order('name')
		results = query.fetch(100, 0)
		return results